import Reflux from 'reflux';
import PageConst from './PageConst';
import Actions from './Actions';
import update from 'react-addons-update';
import nattyStorage from 'natty-storage';
import DB from '../../../app/db';

export default Reflux.createStore({
  listenables: [Actions],
  data: {
    ...PageConst,
    pname: "",
    position: {
      longitude: 111.3007521629,
      latitude: 30.7085782898
    },
    showLoading: true,
    listData: {},
    lineChartsData: [],
    mapInstance: null
  },

  onSetMapInstance: function (mapInstance) {
    this.data.mapInstance = update(this.data.mapInstance, {$set: mapInstance});
    this.updateComponent();
  },

  onLoadData: function (pcode) {
    let that = this;
    DB.WechatAPI.equipmentDetail({
      pcode: pcode
    }).then(
      function (content) {
        console.info(content)
        that.data = update(that.data, {
            position: {
              $set: {
                longitude: content.elng,
                latitude: content.elat
              }
            },
            lineChartsData: {$set: content.lineChartsData},
          }
        );

        if (content.listData.length > 0) {
          that.data.listData = update(that.data.listData, {$set: content.listData[0]});
        } else {
          that.data.listData = update(that.data.listData, {$set: {}});
        }
        that.updateComponent();
        that.onLoadCharts();
      },
      function (error) {
        that.onLoadingControl(false);
        console.log(error);
      }
    );
  },
  onLoadingControl: function (obj) {
    this.data.showLoading = update(this.data.showLoading, {$set: obj});
    this.updateComponent();
  },

  onLoadCharts: function () {
    let that = this;
    let xdata = [];
    let ydata1 = [];
    let ydata2 = [];
    this.data.lineChartsData.map((v, k)=> {
      xdata.push(v.saveTime);
      ydata1.push(v.pmTwo);
      ydata2.push(v.pmTen);
    })

    this.data = update(this.data, {
      qxoption: {
        xAxis: {data: {$set: xdata}},
        series: {
          $apply: (series) => {
            return series.map(item=> {
              if (item.name === 'pm2.5') {
                return update(item, {data: {$set: ydata1}})
              } else {
                return update(item, {data: {$set: ydata2}})
              }
            })
          }
        }
      }
    });
    this.updateComponent();
    that.onLoadingControl(false);
  },


  updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState: function () {
    return this.data;
  }
});
